package lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * @description: 四个核心的函数式接口
 * 1、消费：Consumer<T>     void accept(T);
 * 2、供给：Supplier<T>     T get();
 * 3、函数式：Function<T>   R apply(T t);
 * 4、断定型：Predicate<T>  boolean test(T t)
 * @author: apple
 * @date:  2022/1/3 5:55 下午
 * @version 1.0
 **/
public class LambdaTest3 {

    @Test
    public void test1() {
        // 原来的写法
        happyTime(500, new Consumer<Double>() {
            @Override
            public void accept(Double money) {
                System.out.println("购买：" + money + "的礼品");
            }
        });

        System.out.println("---------");
        // Lambda表达式写法
        happyTime(400,(Double money) -> {
            System.out.println("购买：" + money + "的礼品");
        });
        System.out.println("---------");
        // Lambda表达式简易写法
        happyTime(300,money -> System.out.println("购买：" + money + "的礼品"));

    }

    public void happyTime(double money , Consumer<Double> con) {
        // 回调
        con.accept(money);
    }

    @Test
    public void test2() {

        // 以前写法
        final List<String> list = Arrays.asList("aa", "bbc", "word", "hello");
        final ArrayList<String> strings = filterString(list, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.length() > 2;
            }
        });

        for (String s : strings) {
            System.out.println(s);
        }

        System.out.println("-------");
        // lambda写法
        final ArrayList<String> strings1 = filterString(list, s -> s.length() > 2);
        for (String s : strings1) {
            System.out.println(s);
        }

    }

    public ArrayList<String> filterString(List<String> list, Predicate<String> pre) {

        ArrayList<String> filterList = new ArrayList<>();
        for (String s : list) {
            if (pre.test(s)) {
                filterList.add(s);
            }
        }
        return filterList;
    }

}
